package tiltmaze.view;

import java.awt.Point;
import java.awt.geom.Ellipse2D;

/**
 * Class used for storing the ball information in the graphical representation
 * of a maze.
 * @author Juraj Niznan
 */
public class Ball extends Ellipse2D.Double {

    public static final double R = 1.13;

    private boolean dragged = false;
    private int dragX = 0;
    private int dragY = 0;
    private double ballX = 0;
    private double ballY = 0;
    private int border = MazeCanvas.BORDER;
    private int squareSize = MazeCanvas.SQUARE_SIZE;
    private int numOfCols;
    private int numOfRows;
    private int row;
    private int col;

    private Ball(int centerX, int centerY, int squareSize) {
        super(centerX - (R * squareSize), centerY - (R * squareSize), 2*R * squareSize, 2*R * squareSize);
    }

    public Ball(int row, int col, int numOfRows, int numOfCols) {
        this(MazeCanvas.BORDER + (col * 5 + 3) * MazeCanvas.SQUARE_SIZE, MazeCanvas.BORDER + (row * 5 + 3) * MazeCanvas.SQUARE_SIZE, MazeCanvas.SQUARE_SIZE);
        this.numOfCols = numOfCols;
        this.numOfRows = numOfRows;
        this.row = row;
        this.col = col;
    }

    public void tryDrag(Point p) {
        if (super.contains(p)) {
            dragged = true;
            dragX = p.x;
            dragY = p.y;
            ballX = super.getX();
            ballY = super.getY();
        }

    }

    public void drag(Point p) {
        if (dragged) {
            setFrame(ballX + p.x - dragX, ballY + p.y - dragY, getWidth(), getHeight());
        }
    }

    public void stopDrag() {
        if (dragged) {
            double estimJ = (getCenterX() - border - 3*squareSize)/(5*squareSize);
            double estimI = (getCenterY() - border - 3*squareSize)/(5*squareSize);
            int j = (int) Math.round(estimJ);
            int i = (int) Math.round(estimI);
            j = (j>=numOfCols) ? (numOfCols-1) : ((j<0) ? 0 : j);
            i = (i>=numOfRows) ? (numOfRows-1) : ((i<0) ? 0 : i);
            setFrame(border + (j*5+3-R)* squareSize, border + (i*5+3-R)* squareSize, getWidth(), getHeight());
            dragged = false;
            row = i;
            col = j;
        }
    }

    public boolean dragged() {
        return dragged;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }

 }
